import React, { createContext } from 'react';
import classNames from 'classnames';

export const MenuContext = createContext({});
export const Menu = (props) => {
  const { className, style, children, onSelect, bottomRender } = props;
  const classes = classNames('menu', className);

  const handleClick = (pathKey) => {
    if (onSelect) {
      onSelect(pathKey);
    }
  };

  const passedContext = {
    onSelect: handleClick,
  };

  // children 如果不是 MenuItem 或 SubMenu，自动排除以免报错
  const renderChildren = () => {
    return React.Children.map(children, (child) => {
      const { displayName } = child.type;
      if (displayName === 'MenuItem' || displayName === 'SubMenu') {
        return React.cloneElement(child, {
          pathKey: child.props.route?.path,
        });
      }
    });
  };

  return (
    <ul className={classes} style={style}>
      <MenuContext.Provider value={passedContext}>
        <div className="menu-item-container">{renderChildren()}</div>
      </MenuContext.Provider>
      <li className="menu-bottom-content">{bottomRender}</li>
    </ul>
  );
};
Menu.defaultProps = {};

export default Menu;
